package main

import (
	"bufio"
	"fmt"
	_ "gitee.com/jianyun/golang/crdb/tpch"
	"io"
	"os"
	"strconv"
	"strings"
	"time"
)

const (
	order_csv_file      = "/data2/tpch-data/orders.tbl"
	order_csv_file_part = "/data2/tpch-data/orders_part.tbl"

	li_csv_file      = "/data2/tpch-data/lineitem.tbl"
	li_csv_file_part = "/data2/tpch-data/lineitem_part.tbl"

	batch_size = 10000
)

func AddPartition2Csv(src, dest, delimiter string, partitionIndex int) {
	// source source
	source, err := os.Open(src)
	if err != nil {
		panic(err)
	}
	defer source.Close()

	// writer file
	fw, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		panic(err)
	}
	defer fw.Close()

	writer := bufio.NewWriter(fw)
	reader := bufio.NewReader(source)
	count := 0
	for {
		line, _, err := reader.ReadLine()
		if err == io.EOF {
			break
		}

		count++

		row := AddPartition(string(line), delimiter, partitionIndex)

		writer.WriteString(row + "\n")
		if count%batch_size == 0 {
			fmt.Printf("count=%d\n", count)
			writer.Flush()
		}
	}

	writer.Flush()
}

func AddPartition(line, delimiter string, partitionIndex int) string {
	columns := strings.Split(line, delimiter)
	if len(columns) > partitionIndex+1 {
		column := columns[partitionIndex]
		for _, partitionId := range partIds {
			partition := partitions[partitionId]
			date, _ := time.Parse(base_format, column)
			if date.Before(partition.to) && (date.After(partition.from) || date.Equal(partition.from)) {
				line = line + strconv.Itoa(partitionId) + delimiter
			}
		}
	}

	return line
}

func main() {
	// 获取命令行参数
	fmt.Println("命令行参数数量:",len(os.Args))
	for k,v:= range os.Args{
		fmt.Printf("args[%v]=[%v]\n",k,v)
	}

	var table = "orders"
	var database = "tpchp"
	if len(os.Args) > 1 {
		table = os.Args[1]
	}
	fmt.Printf("table=%s\n",table)

	InitPartitions(table, database)
	if ("orders" == table) {
		AddPartition2Csv(order_csv_file,  order_csv_file_part, "|", 4)
	} else {
		AddPartition2Csv(li_csv_file,  li_csv_file_part, "|", 10)
	}
	//AddPartition2Csv(li_csv_file,  li_csv_file_part, "|", 10)
}
